package emulator.hardware.nmos6502.commands;

import emulator.EmulatorException;
import emulator.hardware.HwByte;
import emulator.hardware.nmos6502.Command;
import emulator.hardware.nmos6502.CommandSet;
import emulator.hardware.nmos6502.Cpu6502;
import emulator.hardware.nmos6502.Flags6502;
import emulator.hardware.nmos6502.Operand;
import emulator.hardware.nmos6502.operands.Absolute;
import emulator.hardware.nmos6502.operands.AbsoluteX;
import emulator.hardware.nmos6502.operands.Accumulator;
import emulator.hardware.nmos6502.operands.ZeroPage;
import emulator.hardware.nmos6502.operands.ZeroPageX;

/** ROR (ROtate Right)
 *  
 *  Affects Flags: S Z C
 *  
 *  MODE           SYNTAX       HEX LEN TIM
 *  Accumulator   ROR A         $6A  1   2
 *  Zero Page     ROR $44       $66  2   5
 *  Zero Page,X   ROR $44,X     $76  2   6
 *  Absolute      ROR $4400     $6E  3   6
 *  Absolute,X    ROR $4400,X   $7E  3   7
 *  
 *  ROR shifts all bits right one position. The Carry is shifted into bit 7
 *  and the original bit 0 is shifted into the Carry. 
 */
public class ROR implements Command {

	@Override
	public void execute(Cpu6502 cpu, Operand operand) throws EmulatorException {
		Flags6502 flags = cpu.getFlags();
		HwByte value = operand.getByte();
		boolean carry = value.getBit(0);
		value.shift(-1);
		value.setBit(7, flags.getCarry());
		operand.setByte(value);
		flags.setCarry(carry);
		flags.setNZFromValue(value);
		cpu.setFlags(flags);
	}

	@Override
	public String getName() {
		return "ROR";
	}

	@Override
	public void register(CommandSet cset) {
		cset.defineCommand(0x6A, this, new Accumulator());
		cset.defineCommand(0x66, this, new ZeroPage(), 4);
		cset.defineCommand(0x76, this, new ZeroPageX(), 4);
		cset.defineCommand(0x6E, this, new Absolute(), 4);
		cset.defineCommand(0x7E, this, new AbsoluteX(false), 5);
	}

}
